<?php


namespace app\Utils;


class Util
{
    /**
     * stdClass对象转json
     * @param $stdClass
     * @return mixed
     */
    public static function getModelJson($stdClass)
    {
        return json_decode(json_encode($stdClass,true),true);
    }

    /**
     * json对象转stdClass
     * @param $json
     * @return false|string
     */
    public static function getJsonModel($json)
    {
        return json_encode(json_decode($json,true),true);
    }

    /**
     * 组装返回数据
     * @param $code
     * @param null $database
     * @param string $msg
     * @return array
     */
    public static function returnJson($code,$database=null,$msg="")
    {
        $data = [
            'code'=>$code
        ];
        if(isset($database)){
            $data['data'] = $database;
        }
        if($msg){
            $data['msg'] = $msg;
        }
        return json($data);
    }

    /**
     * 组装返回数据
     * @param $code
     * @param int $count
     * @param null $database
     * @param string $msg
     * @return array
     */
    public static function returnPageJson($code,$count=0,$database=null,$msg="")
    {
        $data = [
            'code'=>$code,
            'count'=>$count,
            'data'=>$database
        ];
        if($msg){
            $data['msg'] = $msg;
        }
        return json($data);
    }

    /**
     * 菜单组装 (递归)
     * @param $data
     * @return mixed
     */
    public static function setMenuArray($pid,$data)
    {
        $menus = [];
        foreach($data as $key => $v)
        {
            if($v['pid']==$pid){
                //$array['id'] = $v['id'];
                $array['title'] = $v['menu_name'];
                $array['icon'] = (!empty($v['icon'])) ? $v['icon']:"";
                unset($data[$key]);
                $array['jump'] = $v['url'];
                $array['list'] = Util::setMenuArray($v['id'], $data);
                $menus[] = $array;
            }
        }
        return $menus;
    }

    /**
     * 菜单组装 (迭代)
     * @param $data
     * @return array
     */
    public static function setMenuArrayOne($data)
    {
        $data = array_column ($data,null,'id' );
        foreach ($data as $key => $val )
        {
            if($val['pid'])
            {
                if(isset($data[$val['pid']]))
                {
                    $data[$val['pid']]['children'][] = &$data[$key];
                }
            }
        }
        foreach($data as $key => $val)
        {
            if($val['pid'])
            {
                unset($data[$key]);
            }
        }
        return $data;
    }

    /**
     * 角色菜单设置
     * @param $data
     * @param $pid
     * @param $tree
     * @param string $menu_ids
     * @return mixed
     */
    public static function setRoleMenuArray($data,$pid,$tree,$menu_ids = [])
    {
        foreach($data as $item){
            if($pid == $item['pid']){
                $arr = [];
                $arr['name'] = $item['menu_name'];
                $arr['value'] = $item['id'];
                if(!empty($menu_ids) && in_array($item['id'],$menu_ids)){
                    $arr['checked'] = $tree;
                }else{
                    $arr['checked'] = false;
                }
                $arr['disabled'] = false;
                $arr['list'] = [];
                //有按钮说明遍历到最后一层了
                $arr['list'] = Util::setRoleMenuArray($data,$item['id'],[],$menu_ids);
                array_push($tree,$arr);
            }
        }
        return $tree;
    }

    /**
     * 生成激活码
     * @param $number
     * @return array
     */
    public static function codeList($number)
    {
        $list = [];
        for ($i = 0; $i < $number; $i++){
            static $guid = '';
            $uid = uniqid ( "", true );
            $data = $i;
            $data .= time();     // 请求那一刻的时间戳
            $data .= $_SERVER ['HTTP_USER_AGENT'];  // 获取访问者在用什么操作系统
            $data .= $_SERVER ['SERVER_ADDR'];      // 服务器IP
            $data .= $_SERVER ['SERVER_PORT'];      // 端口号
            $data .= $_SERVER ['REMOTE_ADDR'];      // 远程IP
            $data .= $_SERVER ['REMOTE_PORT'];      // 端口信息
            $hash = strtoupper(hash('ripemd128',$uid.$guid.md5($data)));
            $guid = substr($hash,0,8 );
            array_push($list,$guid);
        }
        return $list;
    }


    //数组转XML   
    public static function arrayToXml($arr){
        if(!is_array($arr) || count($arr) == 0) return '';
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    /**
     * 随机码
     * @param int $few 几位
     * @param int $type 类型 返回随机码 1：纯数字    2：全英文    3：英文全小写    4 全英小写 文数字混合   5 唯一码
     * @return int|string
     */
    public static function randomCode($few = 6,$type = 1){
        $code = "";
        switch($type){
            case 1:
                $startNum = pow(10,$few-1);
                $endNum = pow(10,$few) - 1;
                $code = rand($startNum,$endNum);
                break;
            case 2:
                $temp = array_merge(range('a','z'),range('A','Z'));
                shuffle($temp);
                $code = implode('',array_slice($temp,0,$few));
                break;
            case 3:
                $temp = array_merge(range('a','z'));
                shuffle($temp);
                $code = implode('',array_slice($temp,0,$few));
                break;
            case 4:
                $temp = array_merge(range('a','z'),range('0','9'));
                shuffle($temp);
                $code = implode('',array_slice($temp,0,$few));
                break;
            case 5:
                $code =  uniqid(rand(100,999));
                break;// 唯一码
        }
        return $code;
    }

    /**
     * 将XML转为array
     * @param $xml
     * @return mixed
     */
    public static function xmlToArray($xml){
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    /**
     * 企业付款请求
     * 发送数据（微信）
     * @param $url
     * @param $postfields
     * @return bool|string
     */
    public static function postWxData($url,$postfields){
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $postfields;
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        //以下是证书相关代码
        $params[CURLOPT_SSLCERTTYPE] = 'PEM';
        $params[CURLOPT_SSLCERT] = getcwd().'/payment/weixin/cert/apiclient_cert.pem';//绝对路径
        $params[CURLOPT_SSLKEYTYPE] = 'PEM';
        $params[CURLOPT_SSLKEY] = getcwd().'/payment/weixin/cert/apiclient_key.pem';//绝对路径
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }

}
